﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Jinjia.Approve.Entity;
using Jinjia.Approve.Entity.Entity;
using Jinjia.Approve.Entity.Entity.JJFlow;
using Jinjia.Approve.IRepository.JJFlow;
using Jinjia.Approve.Model.Input.JJFlow;
using Jinjia.Approve.Model.VM.JJFlow;
using Jinjia.Core.BaseInfrastructure.StorageModel.Model;
using Jinjia.Core.UnitOfWork.UnitOfWorkComponent;
using SqlSugar;

namespace Jinjia.Approve.Repository.JJFlow
{
    public class FlowTemplateRepository : IFlowTemplateRepository
    {
        private readonly ISqlSugarClient _db;

        public FlowTemplateRepository(IUnitOfWork unitOfWork)
        {
            _db = unitOfWork.GetDbClient();
        }

        public async Task<jj_flow_template> GetById(int id)
        {
            var jjFlowTemplate = await _db.Queryable<jj_flow_template>().Where(x => x.id == id).FirstAsync();
            return jjFlowTemplate;
        }

        public async Task<int> Save(jj_flow_template data)
        {
            if (data.id <= 0) //新增
            {
                var id = await _db.Insertable(data).ExecuteReturnIdentityAsync();
                return id;
            }
            else
            {
                await _db.Updateable(data)
                    .Where(x => x.id == data.id)
                    .ExecuteCommandAsync();
                return data.id;
            }
        }

        public async Task<List<jj_flow_template>> GetExistTemplateByName(string name, int id)
        {
            return await _db.Queryable<jj_flow_template>()
                .Where(t => t.template_name == name)
                .Where(t => t.id != id)
                .Where(t => t.deleted == 0)
                .ToListAsync();
        }

        public async Task<PageListSearchResultVM<JJTemplateViewModel>> GetTemplatePageList(JJTemplateSearchCondition searchCondition, int user_id)
        {
            var queryable = _db.Queryable<jj_flow_template, jj_flow_mapping_tbl, erpa_user_tbl, erpa_user_tbl, erpa_function_tbl, erpa_function_tbl>((a, b, d, e,f,g) => new JoinQueryInfos(
                JoinType.Left, a.id == b.template_id,
                JoinType.Left, a.create_user_id == d.id,
                JoinType.Left, a.update_user_id == e.id,
                JoinType.Left,a.page_id == f.id && f.delete_flag == "0" && f.supplier_flag == "2",
                JoinType.Left, a.detail_page_id == g.id && g.delete_flag == "0" && g.supplier_flag == "2"
            ));
            queryable.Where(a => a.deleted == 0);

            if (!string.IsNullOrWhiteSpace(searchCondition.template_name))
            {
                queryable.Where(a => a.template_name.Contains(searchCondition.template_name));
            }

            if (!string.IsNullOrWhiteSpace(searchCondition.modular_name))
            {
                queryable.Where(" b.modular_name like '%" + searchCondition.modular_name + "%' ");
            }

            if (!string.IsNullOrWhiteSpace(searchCondition.create_user_name))
            {
                queryable.Where(" d.user_name = @create_user_name ", new { create_user_name = searchCondition.create_user_name });
            }

            if (!string.IsNullOrWhiteSpace(searchCondition.page_name))
            {
                queryable.Where((a, b, d, e, f, g) => f.function_name.Contains(searchCondition.page_name));
            }

            if (!string.IsNullOrWhiteSpace(searchCondition.detail_page_route_name))
            {
                queryable.Where((a, b, d, e, f, g) => g.function_name.Contains(searchCondition.detail_page_route_name));
            }

            string orderby = " a.create_time desc"; //"a.activity_state desc,a.deleted asc,a.activity_end_time desc,a.create_time desc  ";
            queryable.OrderBy(!string.IsNullOrWhiteSpace(searchCondition.order_by) ? searchCondition.order_by + " " + searchCondition.direction : orderby);


            var newQuery = queryable.Select<JJTemplateViewModel>(
                @" a.id,a.template_name,a.is_submit_user_check,a.is_revoke,a.deleted,a.create_user_id,a.create_time,a.update_user_id,a.update_time,a.remark,
                   a.page_parameter_key,a.detail_page_parameter_key,a.business_table_name,a.logical_deleted_field,
             b.modular_name,b.modular_key,
             d.user_name as create_user_name,e.user_name as update_user_name,
             f.function_name as page_name,
             f.path as page_route,
             g.function_name as detail_page_route_name,
             g.path as detail_page_route");

            var result = await newQuery.ToPageListAsync(searchCondition, new DynamicTableHeaderInput()
            {
                MethodName = "ERPAssistant.Api.Controllers.JJFlowController.GetTemplatePageList",
                UserId = user_id
            });

            return result;
        }

        public async Task<JJTemplateSignleViewModel> GetTemplateDetail(int id)
        {
            var template = await _db.Queryable<jj_flow_template>()
                .Where(t => t.id == id)
                .Select(t => new JJTemplateSignleViewModel()
                {
                    id = t.id,
                    template_name = t.template_name,
                    is_revoke = t.is_revoke,
                    remark = t.remark,
                    is_submit_user_check = t.is_submit_user_check,
                    page_id = t.page_id,
                    page_parameter_key = t.page_parameter_key,
                    detail_page_id = t.detail_page_id,
                    detail_page_parameter_key = t.detail_page_parameter_key,
                    business_table_name = t.business_table_name,
                    logical_deleted_field = t.logical_deleted_field,
                    is_auto_approve = t.is_auto_approve
                })
                .FirstAsync();
            template.page_route =  (await _db.Queryable<erpa_function_tbl>().FirstAsync(x => x.id == template.page_id))?.path;
            template.detail_page_route =(await _db.Queryable<erpa_function_tbl>().FirstAsync(x => x.id == template.detail_page_id))?.path;
            return template;
        }

        public async Task LogicalDelete(int id, int user_id)
        {
            await _db.Updateable<jj_flow_template>()
                .SetColumns(x => new jj_flow_template { update_user_id = user_id, update_time = DateTime.Now, deleted = 1 })
                .Where(x => x.id == id)
                .ExecuteCommandAsync();
        }

        public async Task<int> GetTemplateId(string system_key, string big_modular_key, string modular_key)
        {
            var sqlWhere = new StringBuilder(" deleted=0 ");
            if (!string.IsNullOrWhiteSpace(system_key))
            {
                sqlWhere.Append($" and system_key ='{system_key}'");
            }

            if (!string.IsNullOrWhiteSpace(big_modular_key))
            {
                sqlWhere.Append($" and big_modular_key ='{big_modular_key}'");
            }

            if (!string.IsNullOrWhiteSpace(modular_key))
            {
                sqlWhere.Append($" and modular_key ='{modular_key}'");
            }

            //获取到模板列表
            var template_id = await _db.Queryable<jj_flow_mapping_tbl>().Where(sqlWhere.ToString()).Select(a => a.template_id).FirstAsync();
            return template_id;
        }
    }
}